//
//  UploadViewController.m
//  VmixMobileDemo
//
//  Created by jeffs on 7/21/10.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "UploadViewController.h"
#import "MobileCoreServices/UTCoreTypes.h"


@implementation UploadViewController

@synthesize uploadForm, uploadProgress, uploadComplete, progressBar, selectFileBtn, uploadFileBtn, authorText, titleText, titleBar; 
@synthesize request, imagePickerController, fileURL, selectedFilePath, selectedFileThumb, availableTypes, filePicked;

/*
 // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
    if ((self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil])) {
        // Custom initialization
    }
    return self;
}
*/


// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
    [super viewDidLoad];
	self.titleBar.topItem.title = @"Upload";
	self.titleBar.tintColor = [UIColor darkGrayColor];
	self.imagePickerController = [[UIImagePickerController alloc] init];
	self.availableTypes = [UIImagePickerController availableMediaTypesForSourceType:UIImagePickerControllerSourceTypeCamera];
	self.filePicked = NO;
}


 - (void)viewWillAppear:(BOOL)animated {
	 [super viewWillAppear:animated];
	 [self resetUpload:self];
	 
 }



/*
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
*/

- (IBAction) performUpload:(id)sender{
	
	self.request = [ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://upload.vmixcore.com/vmixcore/upload"]];
	[request setPostValue:self.authorText.text forKey:@"author"];
	[request setPostValue:self.titleText.text forKey:@"title"];
	[request setPostValue:UTOKEN forKey:@"token"];
	[request setTimeOutSeconds:20];
	[request setUploadProgressDelegate:self.progressBar];
	[request setDelegate:self];
	[request setDidFailSelector:@selector(uploadFailed:)];
	[request setDidFinishSelector:@selector(uploadFinished:)];
	[request setFile:[self.fileURL relativePath] forKey:@"file_upload"];
	[request startAsynchronous];
	self.uploadForm.hidden = YES;
	self.uploadProgress.hidden = NO;

}

- (IBAction) selectFile:(id)sender{
	
	UIActionSheet *actionSheet;
	actionSheet = [[UIActionSheet alloc] initWithTitle:@"Select Video Source" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:@"Record Video" otherButtonTitles:@"Select from Library", nil ];
	[actionSheet showInView:self.view];
	[actionSheet release];
	

}


-(void) actionSheet:(UIActionSheet *) actionSheet clickedButtonAtIndex:(NSInteger) buttonIndex{
	
	NSString *buttonTitle = [actionSheet buttonTitleAtIndex:buttonIndex];
	if([buttonTitle isEqualToString:@"Record Video"]){
			
		self.imagePickerController.sourceType = UIImagePickerControllerSourceTypeCamera;
		
	}else if([buttonTitle isEqualToString:@"Select from Library"]){
		
		self.imagePickerController.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
		
	}
	self.imagePickerController.videoQuality = UIImagePickerControllerQualityTypeHigh;
	self.imagePickerController.mediaTypes = [NSArray arrayWithObject:(NSString *) kUTTypeMovie];
	self.imagePickerController.delegate = self;
	if(![buttonTitle isEqualToString:@"Cancel"]){
		[self presentModalViewController:self.imagePickerController animated:YES];
	}
	
}


- (void)uploadFailed:(ASIHTTPRequest *)theRequest
{
	
	[request cancel];
	NSString *title = [NSString stringWithFormat:@"Upload Failed!"];
	NSString *alertMessage = @"Please retry your upload";
	NSString *ok = [NSString stringWithFormat:@"Ok"];
	UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:alertMessage  delegate:self cancelButtonTitle:ok otherButtonTitles:nil];
	[alert show];
	[alert release];

}

- (void)uploadFinished:(ASIHTTPRequest *)theRequest
{
	//[resultView setText:[NSString stringWithFormat:@"Finished uploading %llu bytes of data",[theRequest postLength]]];
	self.uploadForm.hidden = YES;
	self.uploadProgress.hidden = YES;
	self.uploadComplete.hidden = NO;
	self.filePicked = NO;
	[request cancel];

}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {
	
	if([[info objectForKey: UIImagePickerControllerMediaType] isEqual:(NSString *) kUTTypeMovie]){
		
		self.fileURL = [info objectForKey:UIImagePickerControllerMediaURL];
		self.selectedFilePath.text = [fileURL lastPathComponent];
		self.selectedFileThumb.hidden = NO;
		self.filePicked = YES;
	}
	[self dismissModalViewControllerAnimated:YES];
	
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker {
	
	
	[self dismissModalViewControllerAnimated:YES];
	
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
	
	NSLog(@"%s", __FUNCTION__);
	bool fDidResign = [textField resignFirstResponder];
	//NSLog(@"%s: did %resign the keyboard", __FUNCTION__, fDidResign ? @"" : @"not ");
	return fDidResign;
	
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
	
	//NSLog(@"The Editing has Ended");
	
}

- (BOOL)textFieldShouldEndEditing:(UITextField *)textField {
	// NSLog(@"%s", __FUNCTION__);
	/*
    if( [[textField text] isEqualToString:@"NO!"] ) {
        NSLog(@"%@", textField.text);
        return NO;
    } else {
	 */
        return YES;
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
	
	/*
	if(range.location == 4 && [uITF2 isEqual:textField]){
		uITF2.text = [uITF2.text stringByAppendingString:string];
		[uITF2 resignFirstResponder];	
	}
	 */
	
	return YES;
}

- (IBAction) resetUpload:(id)sender{
	
	
	if([self.availableTypes count] > 1){
		self.uploadForm.hidden = NO;
		self.uploadProgress.hidden = YES;
		self.uploadComplete.hidden = YES;
		if(!self.filePicked){
		self.titleText.text = @"";
			self.selectedFilePath.text = @"No File Selected";
		}
		
	}else{
		
		self.uploadForm.hidden = YES;
		self.uploadProgress.hidden = YES;
		self.uploadComplete.hidden = YES;
		if(!self.filePicked){
		self.titleText.text = @"";
			self.selectedFilePath.text = @"No File Selected";
		}
		
		NSString *title = [NSString stringWithFormat:@"Video Recording Capability Required"];
		NSString *alertMessage = @"Uploading video requires a device that supports video recording.";
		NSString *ok = [NSString stringWithFormat:@"Ok"];
		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title message:alertMessage  delegate:self cancelButtonTitle:ok otherButtonTitles:nil];
		[alert show];
		[alert release];
		
	}

}


- (void)didReceiveMemoryWarning {
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}


- (void)dealloc {
    [super dealloc];
	[availableTypes release];
	[imagePickerController release];
	
}


@end
